package com.taptech.doufu.ui.view.topicview;

import android.app.Activity;
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.EventBean;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.bean.cp.ResponseChangeHotCp;
import com.taptech.doufu.bean.cp.ResponseCpIndexDataBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.FlowViewGroup;
import com.taptech.doufu.ui.view.choice.ChoiceUtils;
import com.taptech.doufu.ui.view.readview.util.ScreenUtils;
import com.taptech.doufu.util.AppUtil;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ScreenUtil;

import org.json.JSONArray;

import java.util.List;

/**
 * Created by Administrator on 2017/4/13/013.
 */
public class NovelTopicTagView extends LinearLayout implements View.OnClickListener{

    //热门cp
    private View layReplace;
    private ImageView ivReplace;
    private FlowViewGroup mFlowViewGroup;
    private String ChangStringUrl;
    private int ChangStringUrlLast;
    private Context context;
    private View rootView;
    private View hotCpTagView;
    private View home_tag_layout;
    private TextView recommend_text;
    private String sexType;
    private String pageType;
    private EventBean eventBean;

    public NovelTopicTagView(Context context) {
        super(context);
        this.context = context;
    }

    public NovelTopicTagView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NovelTopicTagView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public NovelTopicTagView(final Context context, ResponseCpIndexDataBean.DataBean.ListBean model, final String type,int listPos,String pageType){
        this(context);
        rootView = LayoutInflater.from(context).inflate(R.layout.home_tag_item_viewholder_layout, null);
        eventBean = new EventBean();
        eventBean.setCardType(model.getModel());
        eventBean.setMoreType(model.getType());
        eventBean.setTitle(model.getTitle());
        eventBean.setPosition(listPos);

        initViewHotTag(model.getTitle());
        setTags(model.getList());
        if (!TextUtils.isEmpty(model.getTitle())) {
            recommend_text.setText(model.getTitle());
        }
        String tempUrl = model.getMore_url();
        if (tempUrl.contains("&last=")){
            int index = tempUrl.lastIndexOf("&last=");
            if (tempUrl.length()>index){
                ChangStringUrl = tempUrl.substring(0, index);
                try {
                    ChangStringUrlLast = Integer.parseInt(tempUrl.substring(index+6));
                } catch (Exception e) {

                }
            }else{
                ChangStringUrl = model.getMore_url();
                ChangStringUrlLast = model.getLast();
            }
        }else{
            ChangStringUrl = model.getMore_url();
            ChangStringUrlLast = model.getLast();
        }
        changeDayModelBg();
        this.sexType = type;
        this.pageType = pageType;
        addView(rootView);
    }

    public void refrush(ResponseCpIndexDataBean.DataBean.ListBean model){
        if (model != null) {
            initViewHotTag(model.getTitle());
            setTags(model.getList());
            ChangStringUrl = model.getMore_url();
            ChangStringUrlLast = model.getLast();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layReplace://换一批
                UmengEventUtil.addRightTopBtnEvent(context,eventBean,sexType,pageType);
                if (ChangStringUrl != null) {
                    AppUtil.ratateImageView(ivReplace);
                    rxChangeHotCpTag();
                }
                break;
        }
    }

    /**
     * 换一批
     */
    private void rxChangeHotCpTag() {
        if (ChangStringUrl == null) {
            return;
        }
        ApiClient.getInstance().setUseCache(false).getService().getChangeHotCpTag(String.valueOf(ChangStringUrlLast))
                .compose(RxJavaHelper.<ResponseChangeHotCp>observeOnMainThread((Activity) context))
                .subscribe(new BaseSubscriber<ResponseChangeHotCp>() {
                    @Override
                    public void onNext(ResponseChangeHotCp responseCpIndexDataBean) {
                        loadHotCpTagData(responseCpIndexDataBean);
                    }
                });
    }

    /**
     * 加载热门 cp 数据
     */
    private void loadHotCpTagData(ResponseChangeHotCp responseCpIndexDataBean) {
        setTags(responseCpIndexDataBean.getData().getItems());
        ChangStringUrlLast = Integer.valueOf(responseCpIndexDataBean.getData().getLast());
    }



    /**
     * 热门cp 数据
     */
    private void setTags(final List<JsonElement> list) {
        mFlowViewGroup.removeAllViews();
        mFlowViewGroup.setViewMarginHorizontal(ScreenUtil.dip2px(context,8));
        mFlowViewGroup.setViewMarginVertical(ScreenUtil.dip2px(context,8));
        try {
            JSONArray jsonArray = new JSONArray(list.toString());
            List<TagsBean> tagsBeanList = DiaobaoUtil.json2list(TagsBean.class, jsonArray);
            // 设置标签栏的标签
            if (tagsBeanList != null) {
                for (int i = 0; i < tagsBeanList.size(); i++) {
                    final TagsBean model = tagsBeanList.get(i);
                    if (TextUtils.isEmpty(model.getName())) {
                        continue;
                    }
                    TextView text = new TextView(context);
                    text.setClickable(true);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, ScreenUtils.dpToPxInt(27f));
                    text.setLayoutParams(params);
                    text.setTextSize(12f);
                    text.setText(model.getName());
                    text.setGravity(Gravity.CENTER);
                    if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                        text.setTextColor(ContextCompat.getColor(context,R.color.text_color_47));
                        text.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                    }else{
                        text.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));
                        text.setBackgroundResource(R.drawable.bg_tag_gray);
                    }
                    text.setPadding(ScreenUtils.dpToPxInt(15f), ScreenUtils.dpToPxInt(5f), ScreenUtils.dpToPxInt(15f), ScreenUtils.dpToPxInt(5f));
                    text.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ChoiceUtils.jumpTagDetail(getContext(),model.getName());
                        }
                    });
                    mFlowViewGroup.addView(text);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 热门 cp tag view
     */
    private void initViewHotTag(String title) {
        if (rootView == null) {
            return;
        }
        recommend_text = (TextView) rootView.findViewById(R.id.recommend_text);
        layReplace =  rootView.findViewById(R.id.layReplace);
        layReplace.setTag(title);
        layReplace.setOnClickListener(this);
        ivReplace = (ImageView) rootView.findViewById(R.id.ivReplace);
        mFlowViewGroup =  rootView.findViewById(R.id.mFlowViewGroup);
        hotCpTagView = rootView.findViewById(R.id.fg_hot_gay_layout);
        home_tag_layout = rootView.findViewById(R.id.home_tag_layout);
    }

    public void changeDayModelBg(){
        if(WeMediaApplication.getInstance().isDayNightMode_Night){
            darkBg();
        }else {
            dayBg();
        }
    }

    public void dayBg() {
        if (hotCpTagView != null) {
            home_tag_layout.setBackgroundColor(getResources().getColor(R.color.white));
            hotCpTagView.setBackgroundColor(getResources().getColor(R.color.all_activity_bg));
            ivReplace.setAlpha(1.0f);
        }
    }

    public void darkBg() {
        if (hotCpTagView != null) {
            home_tag_layout.setBackgroundColor(getResources().getColor(R.color.fg_dark));
            hotCpTagView.setBackgroundColor(getResources().getColor(R.color.bg_dark));
            ivReplace.setAlpha(Constant.imagViewAlpha);
        }

    }
}
